<template>
  <div class="example-wrapper">
    <button class="btn" @click="create();dialogFormVisible = true" >create</button>
    <button class="btn" @click="remove()" >remove</button>
    <button class="btn" @click="edit()">edit</button>
    <button class="btn" @click="get()" >shuaxin</button>
    <!-- twtree -->
    <div class="panel">
      <TWTree :tree="tree"  ref="tree" @move="mymoveterr" :defaultAttrs="{
        style: {
            fontSize: '16px',
            indent: '35px'
        }
      }"
@blur="blur" class="tree" />
    </div>
    <div>
<!-- 添加dialog -->
<el-dialog title="添加导航菜单" :visible.sync="dialogFormVisible" @close="dialogclose">
  <el-form :model="form" :rules="rules" ref="addformref">
    <el-form-item label="菜单名称" prop="name" :label-width="formLabelWidth">
      <el-input v-model="form.name" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="菜单英文名称" prop="ename" :label-width="formLabelWidth">
      <el-input v-model="form.ename" autocomplete="off"></el-input>
    </el-form-item>

    <el-form-item label="模板"  prop="template" :label-width="formLabelWidth">
      <el-select v-model="form.template" placeholder="请选择页面模板">
        <el-option label="模板一" value=1></el-option>
        <el-option label="模板二" value=2></el-option>
        <el-option label="模板三" value=3></el-option>
      </el-select>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="savecreate();">确 定</el-button>
  </div>
</el-dialog>
    </div>

<!-- 更新dialog -->
    <div>
<el-dialog title="更新导航菜单信息" :visible.sync="dialogForm2Visible" @close="updatedialogclose">
  <el-form :model="form2" :rules="rules" ref="updateformref">
    <el-form-item label="菜单名称" prop="name" :label-width="formLabelWidth">
      <el-input v-model="form2.name" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="菜单英文名称" prop="ename" :label-width="formLabelWidth">
      <el-input v-model="form2.ename" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="模板" prop="template" :label-width="formLabelWidth">
      <el-select v-model="form2.template" placeholder="请选择页面模板">
        <el-option label="模板一" value=1></el-option>
        <el-option label="模板二" value=2></el-option>
        <el-option label="模板三" value=3></el-option>
      </el-select>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogForm2Visible = false">取 消</el-button>
    <el-button type="primary" @click="saveedit ()">更新</el-button>
  </div>
</el-dialog>
    </div>
  </div>

</template>

<script>
// import axios from "../axios"
// import axios from "axios"
// import axios from "../../api/axios.js"
import TWTree from "twtree"
export default {
  name: "getting-started-basic-operations-example",
  components: {
    TWTree
  },
  data () {
    return {
      counter: 100,
      keyword: "",
      treechilddemo: {
        id: null,
        title: null
      },
      treedemo: {
        id: null,
        title: "ROOT",
        hasChild: true,
        children: []
      },
      tree: [],
      dialogFormVisible: false,
      dialogForm2Visible: false,
      form: {
        name: "",
        ename: "",
        template: ""
      },
      form2: {
        name: "",
        ename: "",
        template: ""
      },
      formLabelWidth: "120px",
      rules: {
        name: [{required: true, message: "请输入名称", trigger: "blur"}],
        ename: [{required: true, message: "请输入英文名称", trigger: "blur"}],
        template: [{required: true, message: "请选择模板", trigger: "change"}]
      }

    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert("submit!")
        } else {
          console.log("error submit!!")
          return false
        }
      })
    },
    dialogclose () {
      this.$refs.addformref.resetFields()
    },
    updatedialogclose () {
      this.$refs.updateformref.resetFields()
    },
    get () {
      let _this = this
      this.$forceUpdate()
      this.tree = []
      this.$forceUpdate()
      _this.$request.gettreejson().then(res => {
        // _this.treea = res.data
        let tree1 = res.data
        for (let i = 0; i < tree1.length; i++) {
          let childrens = tree1[i].Childrens
          let treedemo = JSON.parse(JSON.stringify(_this.treedemo))
          treedemo.id = tree1[i].Id
          treedemo.title = tree1[i].Name

          for (let j = 0; j < childrens.length; j++) {
            let onechildern = JSON.parse(JSON.stringify(_this.treechilddemo))
            onechildern.id = childrens[j].Id
            onechildern.title = childrens[j].Name
            treedemo.children.push(onechildern)
          }
          tree1.children = childrens
          _this.tree.push(treedemo)// C# 的数组 add（）
        }
        this.$forceUpdate()
        // console.log(res.data)
      }).catch((err) => {
        console.log(err)
      })
    },
    blur (node) {
      let tree = this.$refs.tree
      tree.quitEdit(node)
    },
    create () {
      this.counter += 1
      let tree = this.$refs.tree
      let node = tree.getSelectedOne()
      console.log(node)
      let child = {
        // id: this.counter,
        title: "请输入导航名称",
        hasChild: false
      }
      tree.create(child, node)
      console.log(tree)
      return node
    },
    savecreate () {
      let _this = this
      this.$refs.addformref.validate((valid) => {
        if (valid) {
          let tree = this.$refs.tree
          let node = tree.getSelectedOne()
          console.log(node)
          if (!node) {
            this.$request.addmenu({
              name: this.form.name,
              ename: this.form.ename,
              template: parseInt(this.form.template),
              parentid: null
            }).then(res => {
              if (res.status === 200) {
                this.$message({
                  message: "添加成功",
                  type: "success"
                })
              } else {
                this.$message({
                  message: "添加失败",
                  type: "error"
                })
              }
              _this.get()
            }).catch((err) => { console.log(err) })
          }
          if (node) {
            this.$request.addmenu({
              name: this.form.name,
              ename: this.form.ename,
              template: parseInt(this.form.template),
              parentid: node.id}).then(res => {
              if (res.status === 200) {
                this.$message({
                  message: "添加成功",
                  type: "success"
                })
              } else {
                this.$message({
                  message: "添加失败",
                  type: "error"
                })
              }_this.get()
            }).catch((err) => { console.log(err) })
          }
          this.dialogFormVisible = false
        } else {
          console.log("error submit!!")
          return false
        }
      })

      // this.tree = []
      // this.get()
    },
    remove () {
      let _this = this
      let tree = this.$refs.tree
      let node = tree.getSelectedOne()
      console.log(node.id)
      if (node) {
        this.$request.deletemenu({id: node.id}).then(res => {
          if (res.data === false) {
            this.$message({
              message: "此菜单不能删除",
              type: "warning"
            })
          }
          if (res.data === true) {
            this.$message({
              message: "删除成功",
              type: "success"
            })
            console.log(res); _this.get()
          }
        }).catch((err) => { console.log(err) })
      }
      // tree.remove(node)
    },
    saveedit () {
      let _this = this
      let tree = this.$refs.tree
      let node = tree.getSelectedOne()
      this.$refs.updateformref.validate((valid) => {
        if (valid) {
          this.$request.updatemenu({
            name: this.form2.name,
            ename: this.form2.ename,
            template: parseInt(this.form2.template),
            id: node.id}).then(res => {
            if (res.status === 200) {
              this.$message({
                message: "修改成功",
                type: "success"
              })
              this.dialogForm2Visible = false
            } else {
              this.$message({
                message: "修改失败",
                type: "error"
              })
            }_this.get()
          }).catch((err) => { console.log(err) })
        } else {
          console.log("error submit!!")
          return false
        }
      }
      )
    },
    edit () {
      let tree = this.$refs.tree
      let node = tree.getSelectedOne()
      // tree.edit(node)
      if (!node) {
        this.$message({
          message: "请先选择要修改的菜单",
          type: "warning"
        })
      }
      if (node) {
        this.$request.getonemenubyid({id: node.id}
        ).then(res => {
          console.log(res)
          if (res.data.ifdelete === true) {
            this.$message({
              message: "此菜单不能修改",
              type: "warning"
            })
          }
          if (res.data.ifdelete === false) {
            console.log(res); this.form2.name = res.data.Name; this.form2.ename = res.data.EName; this.form2.template = res.data.Template
            this.dialogForm2Visible = true
          }
        }
        ).catch((err) => { console.log(err) })
      }
      // this.get()
      // } else {
      //   console.log("error submit!!")
      // }
    },
    search () {
      let tree = this.$refs.tree
      if (this.keyword === "") {
        tree.clearSearchResult()
      } else {
        tree.search(this.keyword)
      }
    },
    beforeDrag () {
      return false
    },
    refresh () {
      // let _this = this
      this.tree = []
      this.get()
      // _this.$request.gettreejson().then(res => { console.log(res) }).then((err) => { console.log(err) })
    },
    mymoveterr (node, fromParent, fromPos, toParent, toPos) {
      let _this = this
      console.log("自己的点", node)
      console.log("他新的双亲结点", toParent)
      console.log("全局的序号", node.__.gpos)
      console.log("在父级的序号", node.__.pos)
      // console.log("他的位置", toPos)
      if (node.__.depth >= 3) {
        alert("不能出现三级标签")
        _this.get()
      } else {
        if (toParent == null) {
          let id = node.id
          let parentid = null
          let order = node.__.gpos - 0.5
          this.$request.updateorder({id: id, parentid: parentid, order: order}).then(res => { console.log(res) }).then((err) => { console.log(err) })
        } else {
          let id = node.id
          let parentid = toParent.id
          let order = node.__.gpos - 0.5
          this.$request.updateorder({id: id, parentid: parentid, order: order}).then(res => { console.log(res) }).then((err) => { console.log(err) })
        }
        _this.get()
      }
    }
  },
  mounted () {
    this.get()
  }}
</script>

<style scoped>
.panel .tree {
  width: 50%;
}
.btn {
  width: 100px;
  margin-right: 20px;
}
</style>
